﻿using MQTTnet.Protocol;
using Lynn.Infastructure.Extension;
using Lynn.Infastructure.Utils;
using System;
using System.Collections.Generic;
using System.Text;

namespace Lynn.Infastructure.Net.MQTT.BaiduOption
{
    public class BaiduServerOption : IMQTTOptions
    {
        public string IoTCoreId { get; set; }
        public string AppKey { get; set; }
        public string AppSecret { get; set; }
        public MqttQualityOfServiceLevel Level => MqttQualityOfServiceLevel.AtLeastOnce;
        public string UserName { get => $"bceiam@{IoTCoreId }|{AppKey}|{Unix}|SHA256"; set { } }
        public string PassWord { get => CanonicalRequest.ToHMACSHA256(SignKey).ToLower(); set { } }
        public string ClientId { get => $"{IoTCoreId}"; set { } }
        public string Server { get; set; }
        public int? Port { get; set; }
        public string Topic { get; set; }
        private DateTime Time = DateTime.Now;
        private string SignKey => AuthStringPrefix.ToHMACSHA256(AppSecret).ToLower();
        private string Utc => Time.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
        private string AuthStringPrefix => $"bce-auth-v1/{AppKey}/{Utc}/60";
        private string CanonicalRequest => "POST\n/connect\n\nhost:iot.gz.baidubce.com";
        private long Unix => Time.ToUnix();
    public void WithClientId(string clientId)
        {
            this.IoTCoreId = clientId;
        }

        public void WithCredentials(string name, string pass)
        {
            this.AppKey = name;
            this.AppSecret = pass;
        }
        public void WithTcpServer(string server, int? port = null)
        {
            this.Server = server;
            this.Port = port;
        }
    }
}
